var util = require('../../utils/util.js');
var api = require('../../config/api.js');
const app = getApp()

Page({
    data: {
        // 购物车商品列表
        cartGoods: [],
        // 购物车选择的数量
        goodsNumber: 0,
        // 当前合计金额
        goodsPrice: 0,
        // 点开购物车默认全选里面的商品
        checkedAllStatus: true,
        // 滑动删除数据
        startX: 0, //开始坐标
        startY: 0,
        // 根据购物车的数量判断 显示提示
        hasCartGoods: 0,
        // 分页数据 页数
        page: 1,
        // 每页数据的条数
        size: 8,
        // 购物车列表总条数
        count:0,
        // 购物车商品总页数
        allPage:0,
        // loading 控制加载图标的位置
        sysHeight: 0,
        // 控制加载
        loading: 0,
        // 单人购买提示
        BuyRemindShow:false,
    },
    // 取消单人购买提示
    BuyRemindClose() {
        this.setData({
            BuyRemindShow: false
        });
    },
    // 确认取消单人购买须知
    BuyRemind() {
        this.setData({
            BuyRemindShow: false
        });
    },
    onLoad: function () {},
    onShow: function () {
        let info = wx.getSystemInfoSync();
        let sysHeight = info.windowHeight - 100;
        this.setData({
            sysHeight: sysHeight,
            page: 1,
            size: 8,
            count:0,
            allPage:0,
            cartGoods:[],
            loading:0
        });
        // 页面显示
        this.getCartList();
        this.getCartNum();
        wx.removeStorageSync('categoryId');
    },
    toIndexPage: function () {
        wx.switchTab({
            url: '/pages/index/index',
        });
    },
    // 获取购物车列表
    getCartList: function () {
        let that = this;
        let userID = wx.getStorageSync('userID')
        util.requestApi(api.getShoppingCart, {
            userID: userID,
            page: this.data.page,
            size: this.data.size
        }).then(function (res) {
            if (res.code == 200) {
                
                let h = res.content.data.length > 0 ? 1 : 0;
                let goodsList = res.content.data;
                for (let i = 0; i < goodsList.length; i++) {
                    goodsList[i].checked = 1;
                }
                that.setData({
                    cartGoods: that.data.cartGoods.concat(goodsList),
                    count:res.content.count,
                    allPage:Math.ceil(res.content.count / that.data.size),
                    hasCartGoods: h,
                    loading: 1,
                })
                that.countCart();
            }

        })

    },
    // 计算全选商品总数和商品总价
    countCart() {
        let goods = this.data.cartGoods;
        var sumNumber = 0;
        var sumPrice = 0.00;
        for (let i = 0; i < goods.length; i++) {
            if (goods[i].checked == 1) {
                sumNumber += goods[i].count;
                sumPrice += goods[i].price * goods[i].count;
            }
        }
        this.setData({
            goodsNumber: sumNumber,
            goodsPrice: sumPrice
        })
    },
    // 点击全选与全不选
    checkedAll: function () {
        let that = this;
        let goodsList = that.data.cartGoods;
        if (that.data.checkedAllStatus) {
            for (let i = 0; i < goodsList.length; i++) {
                goodsList[i].checked = 0
            }
            that.setData({
                checkedAllStatus: false,
                cartGoods: goodsList
            })
        } else {
            for (let i = 0; i < goodsList.length; i++) {
                goodsList[i].checked = 1
            }
            that.setData({
                checkedAllStatus: true,
                cartGoods: goodsList
            })
        }
        that.countCart();

    },
    // 商品减少
    cutNumber: function (event) {
        let itemIndex = event.target.dataset.index;
        let cartItem = this.data.cartGoods;
        if (cartItem[itemIndex].count - 1 == 0) {
            util.showErrorToast('删除左滑试试')
        } else {
            cartItem[itemIndex].count--;
            this.setData({
                cartGoods: cartItem,
            });
            this.countCart();
        }
    },
    // 增加商品
    addNumber: function (event) {
        let Index = event.target.dataset.index;
        let cartList = this.data.cartGoods
        cartList[Index].count++
        this.setData({
            cartGoods: cartList,
        });
        this.countCart();
    },
    // 获取购物车数量
    getCartNum: function () {
        let userID = wx.getStorageSync('userID')
        if (userID !== '' && userID !== undefined) {
            util.requestApi(api.getUserCartCount, {
                userID: userID
            }).then(function (res) {
                if (res.code === 200) {
                    let cartGoodsCount = '';
                    cartGoodsCount = res.content + '';
                    wx.setTabBarBadge({
                        index: 3,
                        text: cartGoodsCount
                    })
                } else {
                    wx.removeTabBarBadge({
                        index: 3,
                    })
                }
            });
        }
    },
    // 去结算
    checkoutOrder: function () {
        //获取已选择的商品
        util.loginNow();
        let that = this;
        // 暂停单人购买功能 return结束该函数
        // that.setData({
        //     BuyRemindShow:true
        // });
        // return;
        // 支付功能
        let cedGoods = that.data.cartGoods;
        let checked = [];
        for (let i = 0; i < cedGoods.length; i++) {
            if (cedGoods[i].skuID.length > 0 && cedGoods[i].skuPID.length > 0) {
                if (cedGoods[i].checked) {
                    checked[checked.length] = {
                        checkedGoods: cedGoods[i],
                        goodsNumber: cedGoods[i].count,
                        checkedSkuProductInfo: cedGoods[i],
                        skuHave: true
                    }
                }
            }else{
                if (cedGoods[i].checked) {
                    checked[checked.length] = {
                        checkedGoods: cedGoods[i],
                        goodsNumber: cedGoods[i].count,
                        checkedSkuProductInfo: cedGoods[i],
                        skuHave: false
                    }
                }
            }

        }
        app.selectGoods = checked
        if (checked.length <= 0) {
            util.showErrorToast('你好像没选中商品');
            return false;
        }
        wx.navigateTo({
            url: '/pages/order-check/index'
        })
    },
    // 点击控制选中不选中
    checkedItem: function (e) {
        let itemIndex = e.currentTarget.dataset.index;
        let that = this;
        let cartList = that.data.cartGoods;
        cartList[itemIndex].checked = !cartList[itemIndex].checked
        let trueNumber = 0;
        for (let i = 0; i < cartList.length; i++) {
            cartList[i].checked == 1 ? trueNumber++ : ''
        }
        let allSelect = false;
        if (trueNumber == cartList.length) {
            allSelect = true;
        }
        that.setData({
            cartGoods: cartList,
            checkedAllStatus: allSelect
        })
        that.countCart();
    },
    handleTap: function (event) { //阻止冒泡 
    },
    touchstart: function (e) {
        //开始触摸时 重置所有删除
        this.data.cartGoods.forEach(function (v, i) {
            if (v.isTouchMove) //只操作为true的
                v.isTouchMove = false;
        })
        this.setData({
            startX: e.changedTouches[0].clientX,
            startY: e.changedTouches[0].clientY,
            cartGoods: this.data.cartGoods
        })
    },
    //滑动事件处理
    touchmove: function (e) {
        var that = this,
            index = e.currentTarget.dataset.index, //当前索引
            startX = that.data.startX, //开始X坐标
            startY = that.data.startY, //开始Y坐标
            touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
            touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
            //获取滑动角度
            angle = that.angle({
                X: startX,
                Y: startY
            }, {
                X: touchMoveX,
                Y: touchMoveY
            });
        that.data.cartGoods.forEach(function (v, i) {
            v.isTouchMove = false
            //滑动超过30度角 return
            if (Math.abs(angle) > 30) return;
            if (i == index) {
                if (touchMoveX > startX) //右滑
                    v.isTouchMove = false
                else //左滑
                    v.isTouchMove = true
            }
        })
        //更新数据
        that.setData({
            cartGoods: that.data.cartGoods
        })
    },
    /**
     * 计算滑动角度
     * @param {Object} start 起点坐标
     * @param {Object} end 终点坐标
     */
    angle: function (start, end) {
        var _X = end.X - start.X,
            _Y = end.Y - start.Y
        //返回角度 /Math.atan()返回数字的反正切值
        return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
    },
    //删除事件
    deleteGoods: function (e) {
        //获取已选择的商品
        let itemId = e.currentTarget.dataset.id;
        let that = this;
        wx.showModal({
            title: '提示',
            content: '确定要删除该商品吗',
            success(res) {
                if (res.confirm) {
                    util.requestApi(api.delShoppingCart, {
                        cartIDS: [itemId]
                    }).then(function (res) {
                        if (res.code == 200) {
                            that.setData({
                                page: 1,
                                size: 8,
                                count:0,
                                allPage:0,
                                cartGoods:[],
                            })
                            that.getCartList();
                            that.getCartNum();
                            wx.showToast({
                                title: '删除成功',
                                icon: 'success',
                                duration: 2000
                            })
                        }
                    });
                }
            }
        })
    },
    onReachBottom(){
        let that = this;
        if (that.data.page >= that.data.allPage) {
            return false;
        }
        that.setData({
            page: that.data.page + 1
        });
        that.getCartList()
    },
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading()
        this.setData({
            page: 1,
            size: 8,
            count:0,
            allPage:0,
            cartGoods:[],
            loading:0
        })
        this.getCartList();
        this.getCartNum();
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },
})